package controller.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserDao;
import factory.UserFactory;

@WebServlet("/modifyMess")
public class ModifyMessServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			UserDao userDao = UserFactory.getInstance("userdaoimpl", UserDao.class);
			String uemail = request.getParameter("uemail");
			String uphone = request.getParameter("uphone");
			String umessage = request.getParameter("umessage");
			String eRegex = "([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})";
			String pRegex = "1[34578]\\d{9}";
			Pattern pe = Pattern.compile(eRegex);
			Pattern pp = Pattern.compile(pRegex);
			Matcher me = pe.matcher(uemail);
			Matcher mp = pp.matcher(uphone);
			PrintWriter out = response.getWriter();
			System.out.println(me.matches());
			System.out.println(mp.matches());
			if(!me.matches()) {
				out.println("<script>alert('邮箱格式错误！');history.back();</script>") ;
				return ;
			}
			if(!mp.matches()) {
				out.println("<script>alert('电话格式错误！');history.back();</script>") ;
				return ;
			}
			HttpSession session = request.getSession();
			String uname = (String)session.getAttribute("uname");
			int result = userDao.updateUserMess(userDao.getAppointUser(uname), uemail, uphone, umessage);
			if (result == 1) {
				request.getRequestDispatcher("view/index.jsp").forward(request, response);
			}else {
				out.println("<script>alert('修改信息失败，服务器出错，请向我们反馈！');history.back();</script>") ;
				out.close();
			}
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}